package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
@Slf4j
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        Page<CheckGroup> page = checkGroupDao.findPage(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(),page);
    }



    @Override
    public void add(CheckGroup checkGroup, Integer[] ids) {
         checkGroupDao.add(checkGroup);
         if (checkGroup.getId()!=null){
             xunhuan(checkGroup.getId(),ids);
         }
    }

    @Override
    public CheckGroup findById(Integer id) {
       CheckGroup checkGroup = checkGroupDao.findById(id);
        return checkGroup;
    }

    @Override
    public Integer[] findCheckitemById(Integer id) {
        Integer[] ids = checkGroupDao.findCheckitemById(id);
        return ids;
    }

    @Override
    public void edit(Integer[] ids, CheckGroup checkGroup) {
        checkGroupDao.edit(checkGroup);
        checkGroupDao.del(checkGroup.getId());
        xunhuan(checkGroup.getId(),ids);
    }

    @Override
    public void delById(Integer id) {
        int count = checkGroupDao.selectById(id);
        if (count>0){
            throw new BusinessRuntimeException("该检查组被关联,不能删除！");
        }
        checkGroupDao.del(id);
        checkGroupDao.delById(id);

    }

    @Override
    public List findAll() {
        List<CheckGroup> all = checkGroupDao.findAll();
        return all;
    }


    // 添加检查组和检查项的中间表
    public void xunhuan(Integer id,Integer[] ids){
        for (Integer ids1 : ids) {
            checkGroupDao.insertData(id,ids1);
        }
    }


}
